from django.shortcuts import render, HttpResponse
from django.conf import settings
from util.tencent.sms import sms_send_sign
import random
from django_redis import get_redis_connection


# Create your views here.

def sms_send(request):
    """ 发送短信
            ?tpl=login  -> 548762
            ?tpl=register -> 548760
    """
    tpl = request.GET.get('tpl')
    phone = request.GET.get('phone')
    template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
    if not template_id:
        return HttpResponse('模板不存在')
    code = random.randrange(1000, 9999)
    res = sms_send_sign(phone, template_id, [code, 1])
    if res['result'] == 0:
        conn = get_redis_connection()
        conn.set(phone, code, ex=60)
        return HttpResponse('成功')
    else:
        return HttpResponse(res['errmsg'])
